package com.jeeplus.test.jlnu.xlsxManage.service.impl;


import com.alibaba.druid.util.StringUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.jeeplus.sys.service.DictValueService;
import com.jeeplus.sys.service.mapstruct.DictValueWrapper;
import com.jeeplus.test.jlnu.xlsxManage.domain.entity.JlnuXlsxManage;
import com.jeeplus.test.jlnu.xlsxManage.domain.query.XlsxManagePageQuery;
import com.jeeplus.test.jlnu.xlsxManage.domain.query.XlsxManageQuery;
import com.jeeplus.test.jlnu.xlsxManage.mapper.JlnuXlsxManageMapper;
import com.jeeplus.test.jlnu.xlsxManage.service.JlnuXlsxManageService;
import com.jeeplus.test.sysTemplate.domain.FieldInfo;
import com.jeeplus.test.tools.utils.ExcelHeaderGenerator;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Service;


import javax.annotation.Resource;
import java.util.*;

/**
 * 动态表头(JlnuXlsxManage)表服务实现类
 *
 * @author ChiHongYu
 * @since 2025-02-17 15:16:39
 */
@Service("jlnuXlsxManage")
public class JlnuXlsxManageServiceImpl implements JlnuXlsxManageService {
    @Resource
    private JlnuXlsxManageMapper jlnuXlsxManageDao;

    @Resource
    private DictValueService dictValueService;

    @Resource
    private DictValueWrapper dictValueWrapper;
    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public JlnuXlsxManage queryById(Integer id) {
        return this.jlnuXlsxManageDao.queryById(id);
    }


    @Override
    public JlnuXlsxManage queryByType(String type, String officeId) {
        JlnuXlsxManage jlnuXlsxManage = this.jlnuXlsxManageDao.queryByType(type, officeId);
        if (jlnuXlsxManage == null || StringUtils.isEmpty(jlnuXlsxManage.getContent())) {
            return jlnuXlsxManage;
        }

        ObjectMapper mapper = new ObjectMapper();
        try {
            // 解析JSON数组
            JsonNode[] nodes = mapper.readValue(jlnuXlsxManage.getContent(), JsonNode[].class);

            // 使用lambda表达式简化比较器
            Arrays.sort(nodes, (a, b) -> {
                boolean hasNumberA = a.has("number") && !a.get("number").isNull();
                boolean hasNumberB = b.has("number") && !b.get("number").isNull();

                if (hasNumberA && hasNumberB) {
                    return a.get("number").asText().compareTo(b.get("number").asText());
                } else if (hasNumberA) {
                    return -1;
                } else if (hasNumberB) {
                    return 1;
                }
                return 0;
            });

            // 设置排序后的内容
            jlnuXlsxManage.setContent(mapper.writeValueAsString(nodes));
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

        return jlnuXlsxManage;
    }

    @Override
    public JlnuXlsxManage getByOffice(String officeId,
                                      String type,
                                      String name) {
        JlnuXlsxManage jlnuXlsxManage = jlnuXlsxManageDao.getByOffice(officeId, type, name);
        if (jlnuXlsxManage == null) {
            jlnuXlsxManage = jlnuXlsxManageDao.getByOffice(null, type, null);
            jlnuXlsxManage.setId(null);
        }
        return jlnuXlsxManage;
    }

    /**
     * 新增数据
     *
     * @param param 实例对象
     * @return 是否成功
     */
    @Override
    public boolean insertOrUpdate(XlsxManageQuery param) {
        if (param.getId() != null) {
            JlnuXlsxManage XlsxManage = jlnuXlsxManageDao.queryById(param.getId());
            if (XlsxManage != null) {
                XlsxManage.setContent(param.getContent());
                return jlnuXlsxManageDao.update(param.makeUpdateEntity(XlsxManage));
               }
            }
        return jlnuXlsxManageDao.insert(param.makeCreateEntity());
    }

    /**
     * 修改数据
     *
     * @param jlnuXlsxManage 实例对象
     * @return 是否成功
     */
    @Override
    public boolean update(JlnuXlsxManage jlnuXlsxManage) {
        return this.jlnuXlsxManageDao.update(jlnuXlsxManage);
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Integer id) {
        return this.jlnuXlsxManageDao.deleteById(id);
    }

    /**
     * 通过主键修改使用状态
     *
     * @param id       主键
     * @param useState 使用状态
     * @return 是否成功
     */
    @Override
    public boolean changeUseById(Integer id, String useState) {
        return this.jlnuXlsxManageDao.changeUseById(id, useState) > 0;
    }

    @Override
    public HashMap<String, Object> page(XlsxManagePageQuery param, int[] page) {
        HashMap<String, Object> result = new HashMap<>();
        result.put("data", jlnuXlsxManageDao.page(param, page[0], page[1]));
        result.put("total", jlnuXlsxManageDao.count(param));
        result.put("code", "0000");
        result.put("msg", "成功！");
        return result;
    }

    @Override
    public HashMap<String, Object> getList(XlsxManagePageQuery param) {
        HashMap<String, Object> result = new HashMap<>();
        if(param.getType().isEmpty()){
            result.put("data", jlnuXlsxManageDao.getTemplateList());
        }else {
            result.put("data", jlnuXlsxManageDao.getList(param));
        }
        result.put("code", "0000");
        result.put("msg", "成功！");
        return result;
    }

    @Override
    public org.springframework.core.io.Resource customizeTemplate(Integer id) {

        JlnuXlsxManage xlsxManage = jlnuXlsxManageDao.queryById(id);
        if (xlsxManage == null) {
            return null;
        }
        String path = "static/" + xlsxManage.getOfficeId() + "/" + xlsxManage.getName() + ".xlsx";
        String filePath = "." + "/jeeplus-web/src/main/resources/" + path;

        JSONArray jsonArray = JSONArray.fromObject(xlsxManage.getContent());
        List<List<String>> table = new ArrayList<>();
        List<String> names = new ArrayList<>();
        List<String> labels = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            if (object.getBoolean("state")) {
                names.add(object.getString("name"));
                labels.add(object.getString("label"));
            }
        }
        table.add(names);
        table.add(labels);
        if(id == 5){
            ExcelHeaderGenerator.newGenerateExcelWithDoubleHeaders(table, filePath, xlsxManage.getName(),dictValueService,dictValueWrapper);
        }else {
            ExcelHeaderGenerator.generateExcelWithDoubleHeaders(table, filePath, xlsxManage.getName());

        }

        return new FileSystemResource(filePath);
    }

    @Override
    public org.springframework.core.io.Resource rowCustomizeTemplate(Integer id) {
        JlnuXlsxManage xlsxManage = jlnuXlsxManageDao.queryById(id);
        if (xlsxManage == null) {
            return null;
        }
        String path = "static/" + xlsxManage.getOfficeId() + "/" + xlsxManage.getName() + ".xlsx";
        String filePath = "." + "/jeeplus-web/src/main/resources/" + path;

        JSONArray jsonArray = JSONArray.fromObject(xlsxManage.getContent());
        List<List<String>> table = new ArrayList<>();
        List<String> names = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            JSONObject object = jsonArray.getJSONObject(i);
            if (object.getBoolean("state")) {
                names.add(object.getString("name"));
            }
        }
        table.add(names);
        ExcelHeaderGenerator.generateExcelWithDoubleHeaders(table, filePath, xlsxManage.getName());

        return new FileSystemResource(filePath);
    }

    @Override
    public List<FieldInfo> queryObjectById(Integer id) {
        JlnuXlsxManage xlsxManage = jlnuXlsxManageDao.queryById(id);
        if (xlsxManage == null) {
            return null;
        }
        String json = xlsxManage.getContent();
        List<FieldInfo> fieldInfoList = JSON.parseObject(json,
                new TypeReference<List<FieldInfo>>() {});
        return fieldInfoList;
    }
}
